import os
import sys
from config import *
from decOrEnc import *
from fileTools import *
from ui import *


def encrypt(filePath, pwd):
    data = readFile(filePath)
    fileDir = os.path.normpath(os.path.dirname(filePath))
    name = os.path.basename(filePath)

    encName = base64Encode(aesEncrypt(name, pwd))
    encPath = os.path.join(fileDir, encName)

    encData = aesEncrypt(base64Encode(data), pwd)

    if os.path.exists(encPath):
        overWrite = input(f"文件 {encName} 已存在，是(y)否(按换行键)覆盖...")
        if overWrite.lower() != "y":
            sys.exit(0)
    writeFile(encPath, encData)

    print(f"加密成功！文件路径：{encPath}")
    openFileExplorer(encPath, fileDir)


def decrypt(filePath, pwd):
    data = readFile(filePath)
    fileDir = os.path.normpath(os.path.dirname(filePath))
    name = os.path.basename(filePath)

    decName = aesDecrypt(base64Decode(name), pwd)
    decPath = os.path.join(fileDir, decName)

    decData = base64Decode(aesDecrypt(data, pwd))

    if os.path.exists(decPath):
        overWrite = input(f"文件 {decName} 已存在，是(y)否(按换行键)覆盖...")
        if overWrite.lower() != "y":
            sys.exit(0)
    writeFile(decPath, decData)

    print(f"解密成功！文件路径：{decPath}")
    openFileExplorer(decPath, fileDir)


if __name__ == "__main__":
    print(f"Cyan's File Encer / Cyan的文件加密器 v{version} by Cyan3771")
    showDisclaimer()

    mode = getMode()
    file = selectFile()
    pwd = getPassword()

    if mode == "e":
        encrypt(file, pwd)
    else:
        decrypt(file, pwd)
